package com.yang.core.plugins.monitoring;

import com.yang.core.api.RestClientBuilder;
import com.yang.core.config.RestClientProperties;
import com.yang.core.extension.ExtensionPoint;
import com.yang.core.extension.RestClientExtension;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 监控扩展
 * 开箱即用的监控功能
 */
@Slf4j
@ExtensionPoint(
    name = "monitoring",
    description = "监控扩展，提供日志、指标和性能监控",
    category = ExtensionPoint.Category.MONITORING,
    order = 20
)
public class MonitoringExtension implements RestClientExtension {

    private final RestClientProperties.Monitoring monitoringConfig;

    public MonitoringExtension() {
        this.monitoringConfig = null; // 使用默认配置
    }

    public MonitoringExtension(RestClientProperties.Monitoring monitoringConfig) {
        this.monitoringConfig = monitoringConfig;
    }

    @Override
    public void extend(RestClientBuilder builder) {
        if (monitoringConfig == null || !monitoringConfig.isEnabled()) {
            return;
        }

        // 添加日志拦截器
        if (monitoringConfig.isLogRequests() || monitoringConfig.isLogResponses()) {
            builder.addInterceptor(new MonitoringLoggingInterceptor(monitoringConfig));
        }

        // 添加指标收集拦截器
        if (monitoringConfig.isMetricsEnabled()) {
            builder.addInterceptor(new MetricsInterceptor(monitoringConfig));
        }

        // 添加性能监控拦截器
        if (monitoringConfig.isPerformanceMonitoring()) {
            builder.addInterceptor(new PerformanceMonitoringInterceptor(monitoringConfig));
        }

        log.info("启用监控扩展，日志: {}, 指标: {}, 性能监控: {}",
                monitoringConfig.isLogRequests() || monitoringConfig.isLogResponses(),
                monitoringConfig.isMetricsEnabled(),
                monitoringConfig.isPerformanceMonitoring());
    }

    /**
     * 获取监控统计信息
     */
    public Map<String, Object> getStatistics() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("monitoringEnabled", monitoringConfig != null && monitoringConfig.isEnabled());
        stats.put("logRequests", monitoringConfig != null && monitoringConfig.isLogRequests());
        stats.put("logResponses", monitoringConfig != null && monitoringConfig.isLogResponses());
        stats.put("metricsEnabled", monitoringConfig != null && monitoringConfig.isMetricsEnabled());
        stats.put("performanceMonitoring", monitoringConfig != null && monitoringConfig.isPerformanceMonitoring());
        return stats;
    }
}